<template>
  <div class="device-discovery-container">
    <el-card class="device-info-card">
      <template #header>
        <div class="card-header">
          <span>我的设备信息</span>
          <el-button type="primary" @click="showRenameDialog">重命名设备</el-button>
        </div>
      </template>
      <div class="device-info">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备名称">{{ deviceStore.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="设备ID">{{ deviceStore.currentDeviceId }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>

    <el-card class="device-list-card">
      <template #header>
        <div class="card-header">
          <span>设备发现</span>
          <div>
            <el-tooltip content="刷新设备列表" placement="top">
              <el-button circle type="primary" @click="refreshDeviceList" :loading="deviceStore.loading">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </template>

      <el-table v-if="deviceStore.deviceList.length > 0" :data="deviceStore.deviceList" stripe style="width: 100%" v-loading="deviceStore.loading">
        <el-table-column prop="deviceName" label="设备名称"></el-table-column>
        <el-table-column prop="ipAddress" label="IP地址">
          <template #default="scope">
            {{ formatIpAddress(scope.row.ipAddress) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="在线状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ formatDeviceStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastSeen" label="最后在线时间">
          <template #default="scope">
            {{ formatDateTime(scope.row.lastSeen) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button-group>
              <el-tooltip content="查看详情" placement="top">
                <el-button size="small" type="info" @click="showDeviceDetail(scope.row)">
                  <el-icon><InfoFilled /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="发送消息" placement="top">
                <el-button size="small" type="primary" @click="sendMessage(scope.row)" :disabled="scope.row.status !== 1">
                  <el-icon><ChatDotRound /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="发送文件" placement="top">
                <el-button size="small" type="success" @click="sendFile(scope.row)" :disabled="scope.row.status !== 1">
                  <el-icon><Document /></el-icon>
                </el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="暂无发现设备，请刷新" v-loading="deviceStore.loading">
        <el-button type="primary" @click="refreshDeviceList">刷新设备</el-button>
      </el-empty>
    </el-card>

    <!-- 设备详情对话框 -->
    <device-detail-dialog
      v-model:visible="detailDialogVisible"
      :device="currentDevice"
      @send-message="sendMessage"
      @send-file="sendFile"
    />

    <!-- 重命名设备对话框 -->
    <el-dialog
      title="重命名设备"
      v-model="renameDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="renameForm" ref="renameFormRef" :rules="renameRules" label-width="80px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="renameForm.deviceName" placeholder="请输入设备名称" maxlength="50" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="renameDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRenameDevice" :loading="renamingDevice">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useDeviceStore } from '@/store/deviceStore';
import { formatIpAddress, formatDeviceStatus } from '@/utils/deviceUtils';
import { updateDeviceName } from '@/api/device';
import DeviceDetailDialog from '@/components/DeviceDetailDialog.vue';
import { Refresh, InfoFilled, ChatDotRound, Document } from '@element-plus/icons-vue';

const router = useRouter();
const deviceStore = useDeviceStore();
const detailDialogVisible = ref(false);
const currentDevice = ref({});
const renameDialogVisible = ref(false);
const renameForm = ref({
  deviceName: ''
});
const renameFormRef = ref(null);
const renamingDevice = ref(false);
const refreshTimer = ref(null);

const renameRules = {
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ]
};

// 刷新设备列表
const refreshDeviceList = () => {
  deviceStore.refreshDevices();
};

// 显示设备详情
const showDeviceDetail = (device) => {
  currentDevice.value = { ...device };
  detailDialogVisible.value = true;
};

// 发送消息
const sendMessage = (device) => {
  router.push({
    name: 'Messages',
    query: { deviceId: device.id }
  });
};

// 发送文件
const sendFile = (device) => {
  router.push({
    name: 'FileTransfer',
    query: { deviceId: device.id }
  });
};

// 显示重命名对话框
const showRenameDialog = () => {
  renameForm.value.deviceName = deviceStore.deviceName;
  renameDialogVisible.value = true;
};

// 处理设备重命名
const handleRenameDevice = async () => {
  if (!renameFormRef.value) return;
  
  await renameFormRef.value.validate(async (valid) => {
    if (valid) {
      renamingDevice.value = true;
      try {
        await updateDeviceName(deviceStore.currentDeviceId, renameForm.value.deviceName);
        deviceStore.updateDeviceName(renameForm.value.deviceName);
        ElMessage.success('设备重命名成功');
        renameDialogVisible.value = false;
      } catch (error) {
        ElMessage.error('设备重命名失败');
        console.error('设备重命名失败', error);
      } finally {
        renamingDevice.value = false;
      }
    }
  });
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未知';
  const date = new Date(dateTime);
  return date.toLocaleString();
};

// 启动定时刷新
const startAutoRefresh = () => {
  // 每60秒自动刷新一次
  refreshTimer.value = setInterval(() => {
    deviceStore.loadDevices();
  }, 60000);
};

// 停止定时刷新
const stopAutoRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
  }
};

onMounted(() => {
  // 初始化设备信息
  deviceStore.initDevice();
  // 加载设备列表
  deviceStore.loadDevices();
  // 启动定时刷新
  startAutoRefresh();
});

onUnmounted(() => {
  stopAutoRefresh();
});
</script>

<style scoped>
.device-discovery-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.device-info-card {
  margin-bottom: 20px;
}

.device-list-card {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 